package com.darker.secking.controller;

import com.darker.secking.entity.User;
import com.darker.secking.service.IGoodsService;
import com.darker.secking.service.IUserService;
import com.darker.secking.vo.DetailVo;
import com.darker.secking.vo.GoodsVo;
import com.darker.secking.vo.RespBean;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.ValueOperations;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.thymeleaf.context.WebContext;
import org.thymeleaf.spring5.ISpringTemplateEngine;
import org.thymeleaf.spring5.view.ThymeleafViewResolver;
import org.thymeleaf.util.StringUtils;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.time.LocalDateTime;
import java.time.temporal.ChronoUnit;
import java.util.concurrent.TimeUnit;

@Controller
@RequestMapping("/goods")
@Slf4j
public class GoodsController {

    @Autowired
   private IUserService userService;

    @Autowired
    private IGoodsService goodsService;

    @Autowired
    private RedisTemplate redisTemplate;

    @Autowired
    private ThymeleafViewResolver thymeleafViewResolver;

    //    @RequestMapping("/toList")
//    public String toLogin(HttpServletRequest request, HttpServletResponse response,Model model, @CookieValue("userTicket") String ticket){
//        if(StringUtils.isEmpty(ticket)){
//            return "login";
//        }
//        User user = userService.getUserByCooike(ticket,request,response);
//        if (user==null){
//            return "login";
//        }
//        model.addAttribute("user",user);
//        return "goodsList";
//    }
    @RequestMapping(value = "/toList",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toLogin(Model model, User user
    , HttpServletRequest request, HttpServletResponse response) {
        //从redis缓存中获取商品列表页面
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html = (String) valueOperations.get("goodsList");
        //如果redis中有商品列表页面 则直接返回
        if(!StringUtils.isEmpty(html)){
            return html;
        }
        model.addAttribute("user", user);
        model.addAttribute("goodsList",goodsService.findGoodsVo());

        //如果没有则通过thymeleaf进行渲染页面
        ISpringTemplateEngine templateEngine = thymeleafViewResolver.getTemplateEngine();//获取模板引擎
        WebContext webContext = new WebContext(request,response,request.getServletContext(),
                request.getLocale(),model.asMap());


         html = templateEngine.process("goodsList", webContext);
         if(!StringUtils.isEmpty(html)){
             valueOperations.set("goodsList",html,1, TimeUnit.MINUTES);
         }
         return html;
    }
    @RequestMapping(value = "/toDetail2/{goodsId}",produces = "text/html;charset=utf-8")
    @ResponseBody
    public String toDetail2(@PathVariable Long goodsId,Model model,User user
    ,HttpServletRequest request,HttpServletResponse response){
        //从redis缓存中获取商品详细页面
        ValueOperations valueOperations = redisTemplate.opsForValue();
        String html= (String) valueOperations.get("goodsDetail:" + goodsId);
        if(!StringUtils.isEmpty(html)){
            return html;
        }
        model.addAttribute("user",user);
        GoodsVo goodsVo = goodsService.findGoodsById(goodsId);
        LocalDateTime startDate = goodsVo.getStartDate();
        LocalDateTime endDate = goodsVo.getEndDate();
        LocalDateTime nowDate = LocalDateTime.now();
//      秒杀状态
        int seckingStatus = 0;

//        秒杀倒计时(秒)
        long remainSeconds=0;
        if(nowDate.isBefore(startDate)){
//            秒杀还没开始  需要设置倒计时
        remainSeconds=nowDate.until(startDate, ChronoUnit.SECONDS);
        }else if(nowDate.isAfter(endDate)){
//            秒杀已经结束
            seckingStatus=2;
            remainSeconds=-1;
        }else if(nowDate.isBefore(endDate)&&nowDate.isAfter(startDate)){
            seckingStatus=1;
            remainSeconds=0;
        }
        model.addAttribute("remainSeconds",remainSeconds);
        model.addAttribute("seckingStatus",seckingStatus);
        model.addAttribute("goods",goodsVo);
//        return "goodsDetail";

        WebContext webContext = new WebContext(request, response, request.getServletContext(),
                request.getLocale(), model.asMap());
        ISpringTemplateEngine templateEngine = thymeleafViewResolver.getTemplateEngine();
        html = templateEngine.process("goodsDetail", webContext);
        if(!StringUtils.isEmpty(html)){
            valueOperations.set("goodsDetail:"+goodsId,html,1,TimeUnit.MINUTES);
        }

        return html;
    }



    @RequestMapping(value = "/detail/{goodsId}",produces = "application/json;charset=utf-8")
    @ResponseBody
    public RespBean toDetail(@PathVariable Long goodsId, User user){

        GoodsVo goodsVo = goodsService.findGoodsById(goodsId);
        LocalDateTime startDate = goodsVo.getStartDate();
        LocalDateTime endDate = goodsVo.getEndDate();
        LocalDateTime nowDate = LocalDateTime.now();
//      秒杀状态
        int seckingStatus = 0;

//        秒杀倒计时(秒)
        long remainSeconds=0;
        if(nowDate.isBefore(startDate)){
//            秒杀还没开始  需要设置倒计时
            remainSeconds=nowDate.until(startDate, ChronoUnit.SECONDS);
        }else if(nowDate.isAfter(endDate)){
//            秒杀已经结束
            seckingStatus=2;
            remainSeconds=-1;
        }else if(nowDate.isBefore(endDate)&&nowDate.isAfter(startDate)){
            seckingStatus=1;
            remainSeconds=0;
        }
        DetailVo detailVo=new DetailVo();
        detailVo.setUser(user);
        detailVo.setGoodsVo(goodsVo);
        detailVo.setRemainSeconds(remainSeconds);
        detailVo.setSeckingStatus(seckingStatus);
        return RespBean.success(detailVo);
    }
}
